package com.oa.srms.apps.timer;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;

import com.oa.srms.apps.business.student.IStudentInfoService;
import com.oa.srms.apps.constants.IDEDStates;
import com.oa.srms.apps.constants.IStudentStates;
import com.oa.srms.apps.entity.student.StudentInfoValue;

public class SendMailService {
	@Autowired
	private IStudentInfoService studentInfoService;

	private List<StudentInfoValue> stundentList;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public void execute() throws Exception {

		System.out.println("SendMailTimer is start(" + sdf.format(new Date()) + ")");

		stundentList = studentInfoService.queryStudentInfoForSendMail(
				IStudentStates.ALLOCATED, IDEDStates.DISABLE);

		if (stundentList.size() != 0 && stundentList != null) {
			System.out.println("SendMailTimer will send " + stundentList.size() + " mail(s).");
			send(stundentList);
		} else {
			System.out.println("There is no mail to be sent.");
		}

		System.out.println("SendMailTimer is End(" + sdf.format(new Date()) + ")");
	}

	public void send(List<StudentInfoValue> stundentList) throws Exception {
		for (StudentInfoValue studentInfo : stundentList) {

			HtmlEmail email = new HtmlEmail();

			email.setTLS(true);
			email.setHostName("smtp.126.com");
			email.setAuthentication("service_srms@126.com", "2012@srms");
			try {
				// EmailAttachment emailattachment = new EmailAttachment();
				//
				// //emailattachment.setPath("/biao_05.jpg");
				//
				// emailattachment.setURL(new
				// URL("http://fmn.rrimg.com/fmn064/20120523/1600/original_HaAR_716400000ef9125d.jpg"));
				//
				// emailattachment.setDisposition(EmailAttachment.ATTACHMENT);
				//
				// emailattachment.setDescription("This is Smile picture");
				//
				// emailattachment.setName("bulktree.jpg");

				// 发送方
				email.setFrom("service_srms@126.com", "大连理工大学城市学院新生入学管理系统邮件组",
						"UTF-8");
				// 标题
				email.setSubject("录取通知书");
				// 设置字符集
				email.setCharset("UTF-8");

				System.out.println("SendMailTimer is sending("
						+ sdf.format(new Date()) + ")");
				// 内容

				if ("".equals(studentInfo.getMailInfo().getMail()) || studentInfo.getMailInfo().getMail() == null) {
					System.out.println("[" + studentInfo.getStuName()+ "] doesn't the mailbox.");
					continue;
				}

				String verifyStr = studentInfo.getMailInfo().getMail() + "||"+ studentInfo.getMailInfo().getVerifyCode();
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(verifyStr.getBytes());
				String verifyMD5Str = Base64.encodeBase64URLSafeString(md.digest());

				// 接收方
				email.addTo(studentInfo.getMailInfo().getMail(), studentInfo.getStuName(), "UTF-8");

				String template = "<div><table width='1000' height='600' cellpadding='0' cellspacing='0' align='center' background='http://fmn.rrimg.com/fmn064/20120523/1600/original_HaAR_716400000ef9125d.jpg'><tr><td align='center' valign='middle'><table><tr><td colspan='2'><br/><br/<font color='yellow' style='font-family:verdana'><h2>恭喜您，您已被我校录取了！</h2></font></td></tr><tr><td style='width: 120px;'><b>&nbsp;姓名:</b></td><td style='width: 110px'><b>&nbsp;"
						+ studentInfo.getStuName()
						+ "</b></td></tr><tr><td style='width: 120px;'><b>&nbsp;身份证号:</b></td><td style='width: 110px'><b>&nbsp;"
						+ studentInfo.getStuDetail().getIdCard()
						+ "</b></td></tr><tr><td style='width: 120px;'><b>&nbsp;学号:</b></td><td style='width: 110px'><b>&nbsp;"
						+ studentInfo.getStuNo()
						+ "</b></td></tr><tr><td style='width: 120px;'><b>&nbsp;录取专业:</b></td><td style='width: 200px'><b>&nbsp;"
						+ studentInfo.getStuDetail().getMajorInfo().getMajorName()
						+ "</b></td></tr><tr><td style='width: 120px;'><b>&nbsp;网站初始密码:</b></td><td style='width: 110px'><b>&nbsp;"
						+ studentInfo.getStuPwd()
						+ "</b></td></tr><tr><td colspan='2' style='font-size:80%'><br/><br/>&nbsp;&nbsp;&nbsp;请<a href='http://localhost:8080/srms/verifyMail.action?stuNo="
						+ studentInfo.getStuNo()
						+ "&str="
						+ verifyMD5Str
						+ "'>登陆</a>系统网站进行信息确认和补充...(此链接一次有效)</td></tr><table></td></tr></table></div>";

				email.setHtmlMsg(template);

				// email.attach(emailattachment);

				// 发送
				email.send();
				
				if(studentInfo.getStates() == IStudentStates.ALLOCATED )
					studentInfoService.setStudentStates(studentInfo.getId(), IStudentStates.ACTIVE);
				
				System.out.println("[" + studentInfo.getStuName()+ "] mail was sent. Its mailBox is ["+ studentInfo.getMailInfo().getMail() + "]");

				Thread.sleep(10000);
				
			} catch (EmailException e) {
				System.err.println("SendMail Process is exception.");
			} catch (Exception e) {
				System.err.println("SendMail Process is exception.");
			}
		}
	}

}
